#include "Resource.h"

Resource *Resource::instance = nullptr;

Resource *Resource::getInstance()
{
    if (instance == nullptr)
    {
        instance = new Resource();
    }
    return instance;
}

void Resource::quit()
{
    for (auto it = images_map.begin(); it != images_map.end();)
    {
        Image* img = it->second;
        delete img;
        it = images_map.erase(it);
    }
    delete instance;
    instance = nullptr;
}

void Resource::loadImage(const char *name, const char *imgpath,ImageDirect imgdirect)
{
    char buff[BUFSIZ];
    sprintf_s(buff, sizeof(buff), "%s\\%s", resourcepath, imgpath);
    SDL_Surface *sur = IMG_Load(buff);
    if (!sur)
    {
        throw std::runtime_error(std::string("没有找到") + buff);
    }
    auto it = images_map.find(name);
    if (it != images_map.end())
    {
        Image* img = it->second;
        delete img;
    }
    Image* img = new Image();
    img->data = sur;
    img->imgdirect = imgdirect;
    images_map.emplace(name, img);
    SDL_Log("loadImage: %s done", buff);
}

void Resource::setPath(const char *path)
{
    sprintf_s(resourcepath, sizeof(resourcepath), "%s\\resource", path);
}

Image * Resource::getImage(std::string name)
{
    auto it = images_map.find(name);
    
    return it != images_map.end() ? it->second : nullptr;
}
